export function addClass (el, className) {
  if (hasClass(el, className)) {
    return
  }
  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

export function hasClass (el, className) {
  let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

export function removeClass (ele, cls) {
  if (hasClass(ele, cls)) {
    var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}
export function getStyle (obj, property) {
  return document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(obj, false)[property] : obj.currentStyle[property]
}

export function getData (el, name, val) {
  const prefix = 'data-'
  name = prefix + name
  if (val) {
    return el.setAttribute(name, val)
  } else {
    return el.getAttribute(name)
  }
}
export function getByClassName (ele, cls) {
  var children = getChildrens(ele)
  var classList = [];
  /* children.forEach((item) => {
    if (item.className.indexOf(cls) !== -1) {
      classList.push(item)
    }
  }) */
  for (var i = 0; i < children.length; i++) {
    var item = children[i]
    if (item.className.indexOf(cls) !== -1) {
      classList.push(item)
    }
  }
  return classList
}

export function getChildrens (t) {
  var list = [];
  (function getInnerChild (t) {
    var childrenList = t.childNodes
    /* childrenList.forEach(function (element) {
      if (element.nodeType === 1) {
        list.push(element)
        getInnerChild(element)
      }
    }) */
    for (var i = 0; i < childrenList.length; i++) {
      var element = childrenList[i]
      if (element.nodeType === 1) {
        list.push(element)
        getInnerChild(element)
      }
    }
  })(t)
  return list
}
export function preventDefault (e) {
  if (e && e.preventDefault) {
    e.preventDefault()
  } else {
    window.event.returnValue = false
  }
}
export function touchmove (e) {
  preventDefault(e)
}
export function addTouchmove () {
  document.addEventListener('touchmove', touchmove, false)
}
export function removeTouchmove (el, name, val) {
  document.removeEventListener('touchmove', touchmove, false)
}
